package cn.wolfcode.web.interceptors;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.mapper.EmployeeMapper;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.service.impl.PermissionServiceImpl;
import cn.wolfcode.util.RequiredPermission;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

public class CheckPermissionInterceptor implements HandlerInterceptor {

    @Autowired
    private IPermissionService permissionService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws ServletException, IOException {
        //得到当前用户，判断是否为管理员
        Employee employee = (Employee)request.getSession().getAttribute("USER_IN_SESSION");
        if(employee.isAdmin()){
            return true;
        }

        //不是管理员，获取当前需要到控制器请求的处理方法
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        //判断处理方法中是否贴有注解
        RequiredPermission annotation = handlerMethod.getMethodAnnotation(RequiredPermission.class);
        //如果没有注解，则直接放行，如果有，则需要获取注解表达式
        if(annotation==null){
            return true;
        }
        String expression = annotation.expression();

        //查询出当前登录用户拥有的权限
        List<String> permissions = permissionService.selectByElId(employee.getId());
        if(permissions.contains(expression)){
            return true;      //放行
        }
        //跳转到没有权限的页面提示用户
        request.getRequestDispatcher("/WEB-INF/views/common/nopermission.jsp").forward(request,response);

        return false;



    }
}
